/*!
\copyright  Copyright (c) 2025 Qualcomm Technologies International, Ltd.
            All Rights Reserved.
            Qualcomm Technologies International, Ltd. Confidential and Proprietary.
\file
\ingroup    user_eq
\brief      API to store and restore last selected preset and gains to/from a ps key

*/

#include "user_eq_user_settings.h"

#include <ps_key_map.h>
#include <ps.h>
#include <panic.h>

#include <stdlib.h>

#define PS_KEY_USER_EQ_PRESET_INDEX    0
#define PS_KEY_USER_EQ_START_GAINS_INDEX    1

void UserEq_SettingsPopulateFromPsStorage(user_eq_data_t *eq_params)
{
    uint16 ps_key_size = PsRetrieve(PS_KEY_USER_EQ, NULL, 0);

    if(ps_key_size)
    {
        uint16 *data = PanicUnlessMalloc(ps_key_size * sizeof(uint16));
        uint16 retrieved_data_size = 0;
        retrieved_data_size = PsRetrieve(PS_KEY_USER_EQ, data, ps_key_size);
        if(retrieved_data_size != ps_key_size)
        {
            Panic();
        }
        eq_params->selected_eq_bank = data[PS_KEY_USER_EQ_PRESET_INDEX];

        uint8 gains_to_restore = MIN(eq_params->user.number_of_bands, ps_key_size - 1);

        for(uint8 i = 0; i < gains_to_restore; ++i)
        {
            eq_params->user.params[i].gain = data[i+1];
        }

        free(data);
    }
}

void UserEq_SettingsWriteToPsStorage(user_eq_data_t *eq_params)
{
    uint16 i;
    uint16 num_of_words = eq_params->user.number_of_bands + 1;
    uint16 *data = PanicUnlessMalloc(num_of_words * sizeof(uint16));

    data[PS_KEY_USER_EQ_PRESET_INDEX] = eq_params->selected_eq_bank;

    for(i = 0; i < eq_params->user.number_of_bands; ++i)
    {
        data[PS_KEY_USER_EQ_START_GAINS_INDEX + i] = eq_params->user.params[i].gain;
    }

    PsStore(PS_KEY_USER_EQ, data, num_of_words);

    free(data); 
}